package com.platform.modules.alg.alglib.poj2503;

public class Poj2503 {
    private int maxn = 500005;
    private int maxz = 26; // 不同字符个数，例如数字 10，小写字母 26
    int trie[][] = new int[maxn][maxz];
    String word[] = new String[maxn]; // 翻译单词
    int value[] = new int[maxn]; // 值的下标
    boolean end[] = new boolean[maxn]; //标记结束
    int n; // 字符串数
    int tot; // 下标

    // 将字符串 s 插入到字典树中
    void insert(String s, int k) {
        int len = s.length();
        int p = 1;
        for (int i = 0; i < len; i++) {
            int ch = s.charAt(i) - 'a'; // 转换成数字
            if (trie[p][ch] == 0)
                trie[p][ch] = ++tot; // 记录下标
            p = trie[p][ch];
        }
        value[p] = k; // 记录下标
        end[p] = true;
    }

    int query(String s) {
        int len = s.length(), p = 1;
        for (int i = 0; i < len; i++) {
            int ch = s.charAt(i) - 'a'; // 转换成数字
            p = trie[p][ch];
            if (p == 0)
                return 0;
        }
        if (end[p])
            return value[p]; // 返回下标
        return 0;
    }

    public String output = "";

    public String cal(String input) {
        String s, s1;
        tot = 1;
        int i = 1;
        String[] line = input.split("\n");
        int count = 0;
        while (true) {
            s = line[count++];
            if (s.length() == 0)
                break;
            String[] words = s.split(" ");
            this.word[i] = words[0];
            s1 = words[1];
            insert(s1, i);
            i++;
        }
        while (true) {
            if (count == line.length)
                break;
            s = line[count++];
            int k = query(s);
            if (k != 0)
                output += word[k] + "\n";

            else
                output += "eh\n";
        }
        return output;
    }
}
